package com.plumelog.config;


import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import com.plumelog.core.dto.BaseLogMessage;
import com.plumelog.core.dto.RunLogMessage;
import com.plumelog.core.lucene.LuceneClient;
import com.plumelog.lite.client.IndexUtil;
import com.plumelog.lite.client.InitConfig;
import com.plumelog.lite.logback.util.LogMessageUtil;

import java.util.ArrayList;
import java.util.List;

public class LiteAppenderTwo extends AppenderBase<ILoggingEvent> {
    private String appName;
    private String env = "default";
    private String logPath;
    private int keepDay = 30;
    LuceneClient luceneClient = null;

    public LiteAppenderTwo() {
    }


    public String getAppName() {
        return appName;
    }

    public void setAppName(String appName) {
        this.appName = appName;
    }

    public String getEnv() {
        return env;
    }

    public void setEnv(String env) {
        this.env = env;
    }

    public String getLogPath() {
        return logPath;
    }

    public void setLogPath(String logPath) {
        this.logPath = logPath;
    }

    public int getKeepDay() {
        return keepDay;
    }

    public void setKeepDay(int keepDay) {
        this.keepDay = keepDay;
    }

    @Override
    protected void append(ILoggingEvent event) {
        if (event != null) {
            this.send(event);
        }

    }

    protected void send(ILoggingEvent event) {
        BaseLogMessage logMessage = LogMessageUtil.getLogMessage(this.appName, this.env, event);
        if (logMessage instanceof RunLogMessage) {
            if (logMessage != null) {
                List<RunLogMessage> list = new ArrayList<>();
                list.add((RunLogMessage) logMessage);
                try {
                    luceneClient.insertListLog(list, getRunLogIndex());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String getRunLogIndex() {
        if ("day".equals(InitConfig.ES_INDEX_MODEL)) {
            return IndexUtil.getRunLogIndex(System.currentTimeMillis());
        } else {
            return IndexUtil.getRunLogIndexWithHour(System.currentTimeMillis());
        }
    }

    @Override
    public void start() {
        super.start();
        luceneClient = new LuceneClient(logPath);
        InitConfig.keepDays = this.keepDay;
        InitConfig.LITE_MODE_LOG_PATH = this.logPath;
    }
}


